const express = require('express')
const checkToken = require('./middleware')
const Mock = require('mockjs')
const path = require('path')
const fs = require('fs')

const multer = require('multer')
// const upload = multer({dest: 'uploads/'})
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'uploads/')
  },
  filename: function (req, file, cb) {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9)
    cb(null, file.fieldname + '-' + uniqueSuffix)
  }
})
const upload = multer({storage})

const app = express()
app.listen(9000, () => {
  console.log('http://localhost:9000')
})
// 解决跨域
app.use(require('cors')())

// 设置静态资源目录
app.use(express.static('./uploads'))

// post提供，内容为json格式
app.use(express.json())

// app.use(checkToken)


// 用户登录
app.post('/api/login', (req, res) => {
  res.send({
    code: 0,
    msg: 'ok',
    data: {
      // 角色ID
      roleid: 11001,
      nickname: '张小华',
      token: 'fewlfewjklfewjl;few;fjefj;fjefle;fjewfewjfew;fewj;',
      routes: [
        '/admin/dashoard',
        '/admin/user',
        '/admin/role',
        '/admin/auth',
        '/admin/nowplaying',
        '/admin/addnowplaying',
        '/admin/comingsoon'
      ]
    }
  })
})

// 登录成功后，就可以根据用户角色来返回对应的菜单
app.post('/api/menu', (req, res) => {
  res.send({
    code: 0,
    msg: 'ok',
    data: [
      {
        path: '/admin/dashoard',
        icon: 'el-icon-setting',
        name: '后台首页'
      },
      {
        path: 'user',
        icon: 'el-icon-message',
        name: '用户管理',
        children: [
          {
            path: '/admin/user',
            name: '用户列表'
          },
          {
            path: '/admin/role',
            name: '角色列表'
          },
          {
            path: '/admin/auth',
            name: '权限列表'
          },
        ]
      },
      {
        path: 'film',
        icon: 'el-icon-message',
        name: '电影管理',
        children: [
          {
            path: '/admin/nowplaying',
            name: '正在热映'
          },
          {
            path: '/admin/comingsoon',
            name: '即将上映'
          },
        ]
      },
      {
        path: 'order',
        icon: 'el-icon-message',
        name: '订单管理',
        children: [
          {
            path: '/admin/order',
            name: '订单列表'
          },
        ]
      },
    ]
  })
})


// 图片上传
app.post('/api/upfile', upload.single('file'), (req, res) => {
  res.send({
    code: 0,
    msg: 'ok',
    data: {
      path: 'http://localhost:9000/' + req.file.filename
    }
  })
})

app.post('/api/userAdd', (req, res) => {
  // `insert into 表名 (字段1，字段2) values (值1，值2)`
  res.send({
    code: 0,
    msg: 'ok',
    data: req.body
  })
})

// http://mockjs.com/examples.html
app.get('/api/users', (req, res) => {
  // page页码
  let {page = 1} = req.query

  let data = Array(10).fill('').map((_, index) => ({
    id: 10 + index,
    date: Mock.mock('@date()'),
    name: Mock.mock('@cname'),
    address: Mock.mock('@county(true)'),
    ...Mock.mock({
      "sex|1": [
        1,
        2
      ]
    }),
    ...Mock.mock({
      "age|1-200": 10
    })
  }))
  res.send({
    code: 0,
    msg: 'ok',
    data: {
      users: data,
      total: 100
    }
  })
})

app.get('/api/search', (req, res) => {
  // page页码
  let {page = 1, kw = ''} = req.query

  let data = Array(10).fill('').map((_, index) => ({
    id: 10 + index,
    date: Mock.mock('@date()'),
    name: Mock.mock('@cname'),
    address: Mock.mock('@county(true)'),
    ...Mock.mock({
      "sex|1": [
        1,
        2
      ]
    }),
    ...Mock.mock({
      "age|1-200": 10
    }),
    kw
  }))
  res.send({
    code: 0,
    msg: 'ok',
    data: {
      users: data,
      total: 100
    }
  })
})


app.post('/api/delAllusers', (req, res) => {
  let {ids} = req.body
  /// 删除所选中的用户id
  res.send({
    code: 0,
    msg: 'ok',
    data: null
  })
})

app.get('/api/users/:id', (req, res) => {
  let id = +req.params.id
  // 判断id是否是数字，是否为0以上
  // `select * from users where id=${id}`
  res.send({
    code: 0,
    msg: 'ok',
    data: {
      id,
      date1: Mock.mock('@date()'),
      username: Mock.mock('@cname'),
      password: 'admin888',
      ...Mock.mock({
        "sex|1": [
          '先生',
          '女士'
        ]
      }),
      ...Mock.mock({
        "age|1-200": 10
      }),
      avatar: 'http://www.mobiletrain.org/images_index/right-fixed-face.png'
    }
  })
})

app.post('/api/userEdit/:id', (req, res) => {
  let id = +req.params.id
  // `update 表名 set 字段=值,字段=值 where id=${id}`
  res.send({
    code: 0,
    msg: 'ok',
    data: null
  })
})

// 根据当前的用户角色和操作的动作在对应的关系表中去查询当前角色没有权限，有返回1，没有0
app.post('/api/btnRole', (req, res) => {
  let {roleid, action} = req.body
  // `select * from role_auth_table where roleid=${roleid} and type=2 and path='${action}'`
  if (action == 'deluser') {
    res.send({
      code: 0,
      msg: 'ok',
      data: 0
    })
  } else {
    res.send({
      code: 0,
      msg: 'ok',
      data: 1
    })
  }
})

app.post('/api/checkRoleNameExists', (req, res) => {
  res.send({
    code: 0,
    msg: 'ok',
    data: false
  })
})

app.post('/api/roles', (req, res) => {
  res.send({
    code: 0,
    msg: 'ok',
    data: {
      id: Date.now(),
      name: req.body.name
    }
  })
})

app.get('/api/roles', (req, res) => {
  let data = Array(10).fill('').map((_, index) => ({
    id: 10 + index,
    name: Mock.mock('@cname')
  }))
  res.send({
    code: 0,
    msg: 'ok',
    data: {
      roles: data,
      total: 100
    }
  })
})

app.post('/api/doSearchUser', (req, res) => {
  let data = Array(6).fill('').map((_, index) => ({
    id: 10 + index,
    username: Mock.mock('@name'),
    isrole: 0
  }))
  res.send({
    code: 0,
    msg: 'ok',
    data
  })
})


app.get('/api/pAuths', (req, res) => {
  // 获取pid=0的所有的权限
  res.send({
    code: 0,
    msg: 'ok',
    data: [
      {id: 1, name: '后台管理'},
      {id: 2, name: '用户管理'},
      {id: 3, name: '电影管理'},
      {id: 4, name: '日志管理'},
      {id: 5, name: '资讯管理'},
      {id: 6, name: '订单管理'},
    ]
  })
})

app.post('/api/importExcel', (req, res) => {
  res.send({
    code: 0,
    msg: 'ok',
    data: null
  })
})


app.post('/api/upvideo', (req, res) => {
  res.send({
    code: 0,
    msg: 'ok',
    data: {
      path: 'http://localhost:9000/vv.mp4'
    }
  })
})

app.post('/api/uploadChunkFile', upload.single('chunk'), (req, res) => {
  let updirPath = path.resolve('uploads')
  // 得到生成目录的名称
  let dirname = req.body.filename.split('_').shift()
  // 判断当前目录下面有没有此目录
  if (!fs.existsSync(path.join(updirPath, dirname))) {
    fs.mkdirSync(path.join(updirPath, dirname))
  }

  const oldFilepath = path.resolve(req.file.path)
  const newFilepath = path.join(path.dirname(oldFilepath), dirname, req.body.filename)
  // 重命名  同步
  fs.renameSync(oldFilepath, newFilepath)
  res.send({
    code: 0,
    msg: 'ok',
    data: {
      path: `http://localhost:9000/${req.body.filename}`
    }
  })
})

app.get('/api/mergeChunkFile', (req, res) => {
  let hash = req.query.hash || ''
  let extName = req.query.ext || ''
  let updirPath = path.resolve('uploads', hash)
  const newFilePath = updirPath + '.' + extName
  // 如果文件不存在，则创建，文件内容为一个buffer
  !fs.existsSync(newFilePath) ? fs.writeFileSync(newFilePath, Buffer.from('')) : null

  if (!fs.existsSync(updirPath)) {
    res.send({
      code: 1000,
      msg: '没有此目录',
      data: null
    })
    return;
  }
  // 读取目录下面的文件列表
  let dirs = fs.readdirSync(updirPath)
  // 升序 从0开始
  dirs.sort((a, b) => {
    let n1 = +a.match(/\w+\_(\d+)\.\w+$/)[1]
    let n2 = +b.match(/\w+\_(\d+)\.\w+$/)[1]
    return n1 - n2
  })
  for (let i = 0; i < dirs.length; i++) {
    let filename = dirs[i];
    const readFilePath = path.join(updirPath, filename)
    // 追加
    fs.appendFileSync(newFilePath, fs.readFileSync(readFilePath))
    // 删除文件
    fs.unlinkSync(readFilePath)
  }
  // 递归删除目录[文件夹]
  fs.rmSync(updirPath, {recursive: true})
  res.send({
    code: 0,
    msg: 'ok',
    data: {
      path: `http://localhost:9000/${req.query.hash}.${extName}`
    }
  })


})
